package com.sunday.aomicaichang.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.OrderListAdapter;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.OrderProduct;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;



public class BuyOrderListFragment extends BaseFragment {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private int type;
    private int statuses;
    private OrderListAdapter adapter;
    private List<OrderItem> dataSet=new ArrayList<>();

    public static BuyOrderListFragment newInstance(int type, int statuses) {
        BuyOrderListFragment fragment = new BuyOrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putInt("statuses", statuses);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            type=getArguments().getInt("type",0);
            statuses=getArguments().getInt("statuses",0);
        }
        initRecyclerView();
        getData();
    }

    private int lastVisibleItem=1;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private void initRecyclerView(){
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager=new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.horizontal_space_divider).build());
        adapter=new OrderListAdapter(mContext,dataSet);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo=1;
                getData();
            }
        });

        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final OrderItem item= (OrderItem) v.getTag();
                switch (v.getId()){
                    case R.id.order_btn1:
                        switch (item.getOrderStatus()){
                            case ConstValue.STA_ONE:
                              //去支付
                                intent=new Intent(mContext,PayConfirmActivity.class);
                                intent.putExtra("order", item);
                                intent.putExtra("type", 1);
                                startActivity(intent);
                                break;
                            case ConstValue.STA_THREE:
                                //确认收货
                                confirmRecieveOrder(item);
                                break;
                            case ConstValue.STA_FOUR:
                                // 去评价
                                List<String> cartIds = new ArrayList<>();
                                for (OrderProduct i : item.getProducts()) {
                                        cartIds.add(String.valueOf(i.getId()));
                                }
                                //Intent intent=new Intent(mContext,AssessActivity.class);
                                Intent intent=new Intent(mContext,MakeCommentsActivity.class);
                                intent= intent.putExtra("order", item);
                                startActivity(intent);
                                break;
                        }
                        break;
                    case R.id.order_btn:
                        switch (item.getOrderStatus()){
                            case ConstValue.STA_ONE:
//                                intent=new Intent(mContext,AssessActivity.class);
//                                intent= intent.putExtra("order", item);
//                                startActivity(intent);
                            final UIAlertView dialog = new UIAlertView(mContext, "温馨提示", "确实取消订单吗", "取消", "确定");
                            dialog.show();
                            dialog.setClicklistener(new UIAlertView.ClickListenerInterface() {
                                @Override
                                public void doLeft() {
                                    dialog.dismiss();
                                }

                                @Override
                                public void doRight() {
                                    //取消订单
                                    cancelOrder(item);
                                    dialog.dismiss();
                                }
                            });
                            break;

                           default:
                                intent=new Intent(mContext,OrderDetailActivity.class);
                                intent.putExtra("orderId",item.getId());
                                startActivity(intent);
                                 break;
                        }
                        break;
                    case R.id.item_view:
                        intent=new Intent(mContext,OrderDetailActivity.class);
                        intent.putExtra("orderId",item.getId());
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    private void cancelOrder(OrderItem orderItem){
        String nonce=MD5Utils.random();
        String[] str1=new String[]{"orderId","nonce"};
        String[] str2=new String[]{String.valueOf(orderItem.getId()),nonce};
        Call<ResultDO> call= MemberClient.getApiAdapter().cancelOrder(orderItem.getId(),nonce,SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish||response.body()==null){return;}
                if (response.body().getCode()==0){
                    pageNo=1;
                    getData();
                    ToastUtils.showToast(mContext,"取消订单成功");
                }else {
                    ToastUtils.showToast(mContext,response.body().getMessage()+"");
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });

    }

    private void confirmRecieveOrder(OrderItem orderItem){
        String nonce=MD5Utils.random();
        String[] str1=new String[]{"orderId","nonce"};
        String[] str2=new String[]{String.valueOf(orderItem.getId()),nonce};
        Call<ResultDO> call= MemberClient.getApiAdapter().confirmReceive(orderItem.getId(),nonce,SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish||response.body()==null){return;}
                if (response.body().getCode()==0){
                    pageNo=1;
                    getData();
                    ToastUtils.showToast(mContext,"确认收货成功");
                }else {
                    ToastUtils.showToast(mContext,response.body().getMessage()+"");
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }

    private int pageNo=1;
    private int pageSize=10;
    private void getData() {
        String nonce= MD5Utils.random();
        String[] str1=new String[]{"type","orderStatuses","pageSize","pageNumber","nonce"};
        String[] str2=new String[]{String.valueOf(type),String.valueOf(statuses),String.valueOf(pageSize),String.valueOf(pageNo),nonce};
        showLoadingDialog(0);
        Call<ResultDO<List<OrderItem>>> call= MemberClient.getApiAdapter().getOrderList(type,statuses,
                pageSize,pageNo,null,null,nonce,
                SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO<List<OrderItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<OrderItem>>> call, Response<ResultDO<List<OrderItem>>> response) {
                ptrFrame.refreshComplete();
                dissMissDialog();
                if (isFinish||response.body()==null){return;}
                if (response.body().getCode()==0){
                    if (response.body().getResult()==null){return;}
                    if (pageNo==1){
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult().size()==10){
                        isCanloadMore=true;
                        pageNo++;
                    }else {
                        isCanloadMore=false;
                    }
                    if (dataSet.size()>0){
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    }else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<OrderItem>>> call, Throwable t) {
                ptrFrame.refreshComplete();
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        pageNo=1;
        getData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
